package com.freak.kotlinfitnessserver.activity.fragment.viewmodel

import androidx.lifecycle.ViewModel
import androidx.lifecycle.ViewModelProvider
import androidx.lifecycle.viewModelScope
import com.freak.kotlinfitnessserver.room.SupportRangeData
import com.freak.kotlinfitnessserver.room.dao.SupportRangeDataDao
import com.freak.kotlinfitnessserver.util.LogUtil
import com.freak.kotlinfitnessserver.util.ToastUtil
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.launch

class SupportRangeViewModel(private val supportRangeDataDao: SupportRangeDataDao) : ViewModel() {
    companion object {
        const val TAG: String = "SupportRangeViewModel"
    }

    fun insertSupportRangeData(item: SupportRangeData) {
        LogUtil.i(
            DeviceInfoViewModel.TAG,
            "insertSupportRangeData supportRangeType = ${item.supportRangeType}"
        )
        viewModelScope.launch {
            val isSuccess = supportRangeDataDao.insert(item)
            if (isSuccess > 0) {
                ToastUtil.toastShort("插入成功")
            } else {
                ToastUtil.toastShort("插入失败")
            }
        }
    }

    fun updateSupportRangeData(item: SupportRangeData) {
        LogUtil.i(
            DeviceInfoViewModel.TAG,
            "updateSupportRangeData supportRangeType = ${item.supportRangeType}"
        )
        viewModelScope.launch {
            val isSuccess = supportRangeDataDao.update(item)
            if (isSuccess > 0) {
                ToastUtil.toastShort("更新成功")
            } else {
                ToastUtil.toastShort("更新失败")
            }
        }
    }

    fun getFlowSupportRangeList(deviceType: String) {
        val resultList = mutableListOf<SupportRangeData>()
        viewModelScope.launch {
            val flow: Flow<List<SupportRangeData>> =
                supportRangeDataDao.getFlowSupportRangeDataListWithDeviceType(deviceType)
            flow.collect { list ->
                resultList.addAll(list)
            }
        }
    }

    suspend fun getSupportRangeList(deviceType: String): List<SupportRangeData> {
        val resultList = mutableListOf<SupportRangeData>()
        val job = viewModelScope.launch {
            val list = supportRangeDataDao.getSupportRangeDataListWithDeviceType(deviceType)
            resultList.addAll(list)
        }
        job.join()
        return resultList
    }

    class SupportRangeViewModelFactory(private val supportRangeDataDao: SupportRangeDataDao) :
        ViewModelProvider.Factory {
        override fun <T : ViewModel> create(modelClass: Class<T>): T {
            if (modelClass.isAssignableFrom(SupportRangeViewModel::class.java)) {
                @Suppress("UNCHECKED_CAST")
                return SupportRangeViewModel(supportRangeDataDao) as T
            }
            throw IllegalArgumentException("Unknown ViewModel class")
        }
    }
}